package cur.nature.framework.core.util;

import lombok.Data;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * https://www.jb51.net/program/329697fyk.htm
 * 雪花算法生成的ID由以下几部分组成：
 * 符号位（1位）：始终为0，保证生成的ID为正数。
 * 时间戳（43位）：记录生成ID的时间戳，精确到毫秒级。可以使用大约69年的时间。
 * 机器ID（8位）：标识生成ID的机器，可以支持256台机器。
 * 序列号（12位）：同一毫秒内生成的多个ID的序列号，可以支持每毫秒生成4096个ID。
 */
@Data
public class SnowflakeIdUtil {
    private final long twepoch = 1738589989639L; // 起始时间戳 20250203，例如Twitter的Snowflake起始时间
    private final long workerIdBits = 8L;
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long sequenceBits = 12L;
    private final long workerIdShift = sequenceBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits;
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    private static SnowflakeIdUtil idWorker;

    public static void setIdWorker(SnowflakeIdUtil idWorker) {
        SnowflakeIdUtil.idWorker = idWorker;
    }

    public static SnowflakeIdUtil getIdWorker() {
        if (idWorker == null) {
            idWorker = new SnowflakeIdUtil(getWorkId());
        }
        return idWorker;
    }

    public SnowflakeIdUtil(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.workerId = workerId;
    }

    public static long generateId() {
        return SnowflakeIdUtil.getIdWorker().nextId();
    }


    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            // 时钟回拨，等待时间追上
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) {
                try {
                    wait(offset << 1);
                    timestamp = timeGen();
                    if (timestamp < lastTimestamp) {
                        throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
            }
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    private static Long getWorkId(){
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for(int b : ints){
                sums += b;
            }
            return (long)(sums % 256);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0,255);
        }
    }

    public static void main(String[] args) {
        SnowflakeIdUtil idGenerator = new SnowflakeIdUtil(0);
        for (int i = 0; i < 10; i++) {
            System.out.println(idGenerator.nextId());
        }
    }
}

